﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SharpShare.Storage.Searching;

namespace SharpShare.Storage.Filter {
    internal sealed class FilteredSearchEngine : IStorageSearchEngine {
        public FilteredSearchEngine(IStorageSearchEngine baseEngine, FilteredStorageProvider provider) {
            this.Provider = provider;
            this.BaseEngine = baseEngine;
        }

        public FilteredStorageProvider Provider { get; private set; }
        public IStorageSearchEngine BaseEngine { get; private set; }

        #region IStorageSearchEngine Members

        public IEnumerable<IStorageItem> Search(Searching.Parameters.SearchParameter parameter) {
            foreach (IStorageItem result in this.BaseEngine.Search(parameter)) {
                yield return WrapChild(result);
            }
        }

        #endregion

        private FilteredStorageItem WrapChild(IStorageItem item) {
            if (item == null) {
                return null;
            }

            IStorageContainer containerChild = item.AsContainer();

            if (containerChild != null) {
                return FilteredStorageContainer.Create(containerChild, this.Provider.Filter, WrapChild(item.Parent).DemandContainer());
            }

            IStorageFile fileChild = item.AsFile();

            if (fileChild != null) {
                return FilteredStorageFile.Create(fileChild, this.Provider.Filter, WrapChild(item.Parent).DemandContainer());
            }

            return null;
        }
    }
}
